package com.github.pig.goods.bussiness.product.controller;


import com.github.pig.common.util.R;
import com.github.pig.common.web.BaseController;
import com.github.pig.goods.common.util.UploadFile;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URL;

@RestController
@RequestMapping("/upload" )
@Slf4j
public class UpLoadController extends BaseController {



    /**
     * 上传文件
     * 访问路径：https://kyb-pic-server-1257189861.cos.ap-guangzhou.myqcloud.com
     * @param file 资源
     * @return PutObjectResult
     */
    @PostMapping("/up" )
    @ApiOperation(value = "上传文件", notes = "根据不通的type上传文件")
    public R upload(@RequestParam("file" ) MultipartFile file, String type) {
        String uri  =null;
        File newFile = new File(file.getOriginalFilename());

        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
            URL url= UploadFile.picCOS(newFile,type,null);
            log.info("文件上传成功！文件类型为：{},路径为：{}",type,url.toString());
            newFile.delete();

            //第二种拼接方法 腾讯cos 带？后面的参数图片无显示bug
            uri=url.getProtocol()+"://"+url.getHost()+url.getPath();

            //StringUtils.substringBefore(url.toString(),"?")
            return new R<>(uri);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new R();
    }



}

